<template>
  <UserLayout :active-index="activeIndex" :active-menu="activeMenu">
    <div class="maintenance-content">
      <!-- 页面标题 -->
      <div class="page-header">
        <h2>维修申请</h2>
        <el-button type="primary" @click="showApplyDialog = true" icon="Plus">申请维修</el-button>
      </div>

      <!-- 维修申请列表 -->
      <div class="maintenance-list">
        <el-card v-for="item in maintenanceList" :key="item.maintenanceId" class="maintenance-item">
          <div class="maintenance-header">
            <div class="house-info">
              <h3>{{ item.house?.houseSummary || '房源信息' }}</h3>
              <p>{{ item.house?.houseLocation || '位置信息' }}</p>
            </div>
            <div class="status-badge">
              <el-tag :type="getStatusType(item.maintenanceStatus)">
                {{ getStatusText(item.maintenanceStatus) }}
              </el-tag>
            </div>
          </div>
          
          <div class="maintenance-content-detail">
            <p><strong>故障描述：</strong>{{ item.faultDescription }}</p>
            <p><strong>申请时间：</strong>{{ formatDate(item.createTime) }}</p>
          </div>
          
          <div class="maintenance-actions" v-if="item.maintenanceStatus === 0">
            <el-button size="small" @click="viewDetail(item)">查看详情</el-button>
          </div>
        </el-card>
        
        <el-empty v-if="maintenanceList.length === 0" description="暂无维修申请" />
      </div>

      <!-- 申请维修对话框 -->
      <el-dialog v-model="showApplyDialog" title="申请维修" width="600px">
        <el-form :model="applyForm" :rules="applyRules" ref="applyFormRef" label-width="100px">
          <el-form-item label="选择房源" prop="houseId">
            <el-select v-model="applyForm.houseId" placeholder="请选择需要维修的房源" style="width: 100%">
              <el-option
                v-for="house in rentedHouses"
                :key="house.houseId"
                :label="house.houseSummary"
                :value="house.houseId"
              />
            </el-select>
          </el-form-item>
          
          <el-form-item label="故障描述" prop="faultDescription">
            <el-input
              v-model="applyForm.faultDescription"
              type="textarea"
              :rows="4"
              placeholder="请详细描述故障情况"
            />
          </el-form-item>
          
          <el-form-item label="紧急程度" prop="urgency">
            <el-radio-group v-model="applyForm.urgency">
              <el-radio :label="1">一般</el-radio>
              <el-radio :label="2">紧急</el-radio>
              <el-radio :label="3">非常紧急</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="联系电话" prop="contactPhone">
            <el-input v-model="applyForm.contactPhone" placeholder="请输入联系电话" />
          </el-form-item>
          
          <el-form-item label="期望时间" prop="expectedTime">
            <el-input v-model="applyForm.expectedTime" placeholder="请输入期望维修时间" />
          </el-form-item>
          
          <el-form-item label="备注">
            <el-input v-model="applyForm.remarks" placeholder="其他说明" />
          </el-form-item>
        </el-form>
        
        <template #footer>
          <el-button @click="showApplyDialog = false">取消</el-button>
          <el-button type="primary" @click="submitApplication" :loading="submitting">提交申请</el-button>
        </template>
      </el-dialog>
    </div>
  </UserLayout>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import UserLayout from '@/components/layout/UserLayout.vue'
import api from '@/utils/api'
import { getToken } from '@/utils/auth'

const activeIndex = ref('4')
const activeMenu = ref('tenant')

// 维修申请列表
const maintenanceList = ref([])
const loading = ref(false)

// 申请对话框
const showApplyDialog = ref(false)
const submitting = ref(false)
const applyFormRef = ref()

// 租住的房源列表
const rentedHouses = ref([])

// 申请表单
const applyForm = ref({
  houseId: '',
  faultDescription: '',
  urgency: 1,
  contactPhone: '',
  expectedTime: '',
  remarks: ''
})

// 表单验证规则
const applyRules = {
  houseId: [
    { required: true, message: '请选择房源', trigger: 'change' }
  ],
  faultDescription: [
    { required: true, message: '请输入故障描述', trigger: 'blur' },
    { min: 10, message: '故障描述至少10个字符', trigger: 'blur' }
  ],
  urgency: [
    { required: true, message: '请选择紧急程度', trigger: 'change' }
  ]
}

// 获取维修申请列表
const fetchMaintenanceList = async () => {
  loading.value = true
  try {
    const response = await api.get('/maintenance/tenant/list', {
      headers: { info: getToken() }
    })
    if (response.data.code === 200) {
      maintenanceList.value = response.data.data || []
    } else {
      ElMessage.error(response.data.message || '获取维修申请列表失败')
    }
  } catch (error) {
    ElMessage.error('获取维修申请列表失败')
  } finally {
    loading.value = false
  }
}

// 获取租住的房源列表
const fetchRentedHouses = async () => {
  try {
    const response = await api.get('/contract/tenant/houses', {
      headers: { info: getToken() }
    })
    if (response.data.code === 200) {
      rentedHouses.value = response.data.data || []
    }
  } catch (error) {
    console.error('获取租住房源失败:', error)
  }
}

// 提交维修申请
const submitApplication = async () => {
  if (!applyFormRef.value) return
  
  const valid = await applyFormRef.value.validate().catch(() => false)
  if (!valid) return
  
  submitting.value = true
  try {
    const response = await api.post('/maintenance/tenant/apply', applyForm.value, {
      headers: { info: getToken() }
    })
    
    if (response.data.code === 200) {
      ElMessage.success('维修申请提交成功')
      showApplyDialog.value = false
      resetForm()
      fetchMaintenanceList()
    } else {
      ElMessage.error(response.data.message || '提交失败')
    }
  } catch (error) {
    ElMessage.error('提交失败，请重试')
  } finally {
    submitting.value = false
  }
}

// 重置表单
const resetForm = () => {
  applyForm.value = {
    houseId: '',
    faultDescription: '',
    urgency: 1,
    contactPhone: '',
    expectedTime: '',
    remarks: ''
  }
  applyFormRef.value?.resetFields()
}

// 获取状态类型
const getStatusType = (status) => {
  const statusMap = {
    0: 'warning',  // 待处理
    1: 'success',  // 已处理
    2: 'danger'    // 已拒绝
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    0: '待处理',
    1: '已处理',
    2: '已拒绝'
  }
  return statusMap[status] || '未知状态'
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

// 查看详情
const viewDetail = (item) => {
  // 这里可以实现查看详情的逻辑
  ElMessage.info('查看详情功能待实现')
}

// 页面加载时获取数据
onMounted(() => {
  fetchMaintenanceList()
  fetchRentedHouses()
})
</script>

<style scoped>
.maintenance-content {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  box-shadow: 0 4px 15px rgba(102, 126, 234, 0.4);
}

.page-header h2 {
  color: white;
  margin: 0;
  font-size: 24px;
  font-weight: 600;
}

.page-header .el-button {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  color: white;
  backdrop-filter: blur(10px);
}

.page-header .el-button:hover {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.5);
}

.maintenance-list {
  display: grid;
  gap: 20px;
}

.maintenance-item {
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
}

.maintenance-item:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
}

.maintenance-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 15px;
}

.house-info h3 {
  margin: 0 0 5px 0;
  color: #2c3e50;
  font-size: 18px;
}

.house-info p {
  margin: 0;
  color: #7f8c8d;
  font-size: 14px;
}

.maintenance-content-detail {
  margin-bottom: 15px;
}

.maintenance-content-detail p {
  margin: 8px 0;
  color: #34495e;
}

.maintenance-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>
